package com.demo.search;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.filechooser.FileFilter;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 此类为Lucence的一个Demo类
 * 
 * @author ryuu.kk
 *
 */
public class Indexer {
	
	private IndexWriter writer;
	
	public Indexer(String indexDir) throws IOException {
		Directory dir = FSDirectory.open(new File(indexDir));
		IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
		writer = new IndexWriter(dir, writerConfig);
	}
	
	/**
	 * 关闭索引写入流
	 * @throws IOException IO异常
	 */
	public void close() throws IOException {
		writer.close();
	}
	
	public int index(String dataDir, FileFilter filter) throws IOException {
		File[] files = new File(dataDir).listFiles();
		for (File f: files) {
			if (!f.isDirectory() && 
				!f.isHidden() && 
				f.exists() && 
				f.canRead() && 
				(filter == null || filter.accept(f))) {
				indexFile(f);
			}
		}
		
		return writer.numDocs();
	}
	
	protected Document getDocument(File f) throws IOException {
		Document doc = new Document();
		doc.add(new Field("contents", new FileReader(f)));
		doc.add(new Field("filename", f.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED));
		doc.add(new Field("fullpath", f.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
		
		return doc;
	}
	
	private void indexFile(File f) throws IOException {
		System.out.println("Indexing " + f.getCanonicalPath());
		Document doc = getDocument(f);
		writer.addDocument(doc);
	}
	
	public static void main(String[] args) throws Exception {
		
		if (args.length != 2) {
			throw new IllegalArgumentException("Usage: Java" + Indexer.class.getName() + " <index dir> <data dir>");
		}
		String indexDir = args[0];
		String dataDir = args[1];
		
		long start = System.currentTimeMillis();
		Indexer indexer = new Indexer(indexDir);
		int numIndexed;
		try {
			numIndexed = indexer.index(dataDir, new FileFilter(){
				@Override
				public boolean accept(File path) {
					return path.getName().toLowerCase().endsWith(".txt");
				}
				@Override
				public String getDescription() {
					return "text file";
				}
			});
		} finally {
			indexer.close();
		}
		long end = System.currentTimeMillis();
		
		System.out.println("Indexing " + numIndexed + " fileds took " + ( end - start) + " milliseconds");
	}

}
